<?php 
/**
 * Project: HTPHouDuan
 * User: xilibo
 * Date: 2018/1/30
 */

namespace app\common\controller;

use think\Controller;
use think\Config;
use think\Cache;
use think\Exception;
use think\Request;
use app\common\library\Mcrypter;

/**
 * 公共控制器
 */
abstract class CommonController extends Controller
{
	
    // 站点节点
    protected $siteNode;

    // 节点名称
    protected $siteNodeName;

    // 请求的加密参数
    protected $encryptedParams;

    // 解密后的参数
    protected $decryptedParams;

    // 当前用户信息
    protected $curUser = [];

    // 密钥
    protected static $secKey = '';

    // 密码器
    protected static $mcrypter = null;
    
	// 错误码配置
    protected $errorCodes = [];

    protected $errorKey = '';

    protected $jsonOptions = [];

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    protected function _initialize()
    {
    	$this->errorCodes = Config::get('error_code');
    	$this->jsonOptions = ['json_encode_param' => JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT];
    	$this->request = Request::instance();
    }

    /**
     * 当前节点用户验证
     * @return bool
     */
    protected function verifyLogin()
    {
       	$username = trim($this->request->param('username', ''));
       	$code = $this->request->param('code', '');
        $userInfo = session('user');
        $cachedUser = Cache::get('code.' . $code . '.user');
        if (! empty($code) && !empty($username)){
			if ($username == $userInfo['user_login']){
				$this->curUser = $userInfo;
				return true;
			} else if ($username == $cachedUser['user_login']){
                session('user', $cachedUser);
                Cache::rm('code.' . $code . '.user');
                Cache::rm('user.' . $username . '.code');
				$this->curUser = $cachedUser;
				return true;
            } else {
                return false;
            }
		} else if (!empty($userInfo)){
			$this->curUser = $userInfo;		
			return true;
        } else {
            return false;
        }

    }

	/**
     * 返回错误码json
     * @param  string/array  $errorName  错误码名或数组
     * @param  integer $statusCode HTTP状态码
     * @return string              json
     */
    protected function jsonError($errorName = '', $statusCode = 400)
    {
        if (is_string($errorName)){
            if (array_key_exists($errorName, $this->errorCodes)){
                return json($this->errorCodes[$errorName], $statusCode, [], $this->jsonOptions);
            } else {
                $errorCode = $this->errorCodes['param_error'];
                $errorCode['msg'] = $errorName;
                return json($errorCode, $statusCode, [], $this->jsonOptions);
            }
        } else {
            return json($errorName, $statusCode, [], $this->jsonOptions);
        }
    }

    /**
     * 返回成功提示json
     * @param  [type]  $message   消息
     * @param  integer $statusCode HTTP状态码
     * @return string              json
     */
    protected function jsonSuccess($message, $statusCode = 200)
    {
        $arrMessage = ['code' => 0, 'msg' => $message, 'data' => []];
        if (is_array($message)){
            $arrMessage['msg'] = !empty($message['msg']) ? $message['msg'] : 'SUC';
            $arrMessage['data'] = !empty($message['data']) ? $message['data']: [];
            unset($message['msg'], $message['data']);
            $arrMessage = array_merge($arrMessage, $message);
        }

        return json($arrMessage, $statusCode, [], $this->jsonOptions);
    }

    /**
     * 获取加密器
     * @return object Mcrypter
     */
    protected static function getMcrypter()
    {
        static::$secKey = Config::get('api.secret_key', '');
        try {
            $mcrypt = Mcrypter::instance(['secretKey' => static::$secKey]);
            return $mcrypt;
        } catch (Exception $e){
            return null;
        }
    }

}
